


import React ,{ useState, useEffect }from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Link, useHistory, useLocation } from 'react-router-dom';
// 引入二级路由组件
import Admin from '@/router/Admin';
// 引入页面的css 文件
import '@/assets/css/dashboard.css';
// 导入图标
import {
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    AppstoreOutlined,
    PieChartOutlined,
    ExclamationCircleOutlined
} from '@ant-design/icons';
import { Layout, Menu, theme, Button, Modal, message } from 'antd';


// 引入获取登录用户信息接口
import { getadmininfo, jwtPreCheckFn } from '@/api/dashboard';
const { Header, Sider, Content } = Layout;

const Dashboard = () => {
    // 控制左侧菜单折叠变量
    const [collapsed, setCollapsed] = useState(false);
    const {
        token: { colorBgContainer },
    } = theme.useToken();
    // 获取redux 仓库中的store保存的菜单数据acl
    const { acl } = useSelector((state) => state)
    // 左侧menu 菜单的函数
    function getItem(label, key, icon, children, type) {
        return {
            key,
            icon,
            children,
            label,
            type,
        };
    }

    const items = [];
    acl.map((v, i) => {
        if (v.children.length != 0) {
            // 说明 该菜单有二级菜单
            items.push(getItem(v.auth_name, v.auth_path, <AppstoreOutlined />, v.children.map((v1, i1) => {
                // 只渲染 is_nav为1 的菜单项
                // 渲染二级菜单
                if (v1.is_nav == 1) {
                    return getItem(<Link to={v1.auth_path}>{v1.auth_name}</Link>, v1.auth_path)
                }
            })))
        } else {
            // 渲染一级菜单
            items.push(getItem(<Link to={v.auth_path}>{v.auth_name}</Link>, v.auth_path, <PieChartOutlined />))
        }
    })

    // console.log('items', items);
    // 获取用户信息接口
    const [accountInfo, setAccountInfo] = useState({})
    const [islogin, setIslogin] = useState(false)
    useEffect(() => {
        // 获取用户信息接口
        getadmininfo().then(res => {
            // console.log('user', res);
            if (res.data.errNo == 0) {
                setAccountInfo(res.data.accountInfo)
            }
        })

        // 验证token,查看用户是否登录接口,防跳墙功能
        jwtPreCheckFn().then(res => {
            // console.log('check', res);
            if (res.data.errNo != 0) {
                // 没有登录
                message.error('请先登录', 1, () => {
                    his.push('/login')
                })
            } else {
                // 已经登录
                setIslogin(true)
            }
        })

    }, [])

    const dispatch = useDispatch();
    const his = useHistory()
    // 定义退出登录函数
    const loginOut = () => {
        Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined />,
            content: '确认要退出登录吗?',
            okText: '确认',
            cancelText: '取消',
            onCancel: () => { },
            onOk: () => {
                // console.log('点击确定');
                // 没有接口调用, 清除登录时token,user等信息
                //01: 清除 jwt
                localStorage.removeItem('jwt')
                //02: 
                dispatch({ type: 'updateAcl', payload: [] });
                localStorage.removeItem('persist:userAcl');
                //03: 返回登录页
                setTimeout(() => {
                    his.push('/login')
                }, 500)

            }
        });
    }

    // 设置默认选中的菜单项defaultSelectedKeys key 对应的path 路径
    const loc = useLocation();

    return (
        <>
            {
                islogin ? <Layout>
                    <Sider trigger={null} collapsible collapsed={collapsed}>
                        <div className="logo"></div>
                        <Menu
                            theme="dark"
                            mode="inline"
                            defaultSelectedKeys={[loc.pathname]}
                            //设置默认打来的是哪一个一级菜单
                            defaultOpenKeys={[loc.pathname.substring(0, loc.pathname.lastIndexOf('/'))]}
                            items={items}
                        />
                    </Sider>
                    <Layout className="site-layout">
                        <Header
                            style={{
                                padding: 0,
                                background: colorBgContainer,
                                display: 'flex',
                                alignItems: 'center',
                            }}
                        >
                            {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
                                className: 'trigger',
                                onClick: () => setCollapsed(!collapsed),
                            })}
                            <div style={{
                                flex: 1,
                                display: 'flex',
                                justifyContent: 'space-between',
                                alignItems: 'center',
                                paddingLeft: '10px',
                                paddingRight: '10px'
                            }}>
                                {/* 显示用户名和角色 */}
                                <span>您好,{accountInfo.username}/{accountInfo.role}</span>
                                {/* 注销登录按钮 */}
                                <Button onClick={loginOut}>注销登录</Button>
                            </div>
                        </Header>
                        <Content
                            style={{
                                margin: '24px 16px',
                                padding: 24,
                                minHeight: 280,
                                background: colorBgContainer,
                            }}
                        >
                            {/* 改成二级路由组件的坑 */}
                            <Admin></Admin>
                        </Content>
                    </Layout>
                </Layout> : <></>

            }

        </>
    );
}

export default Dashboard;
